<template>
  <view class="page">
    <!-- 公共组件-每个页面必须引入 -->
    <public-module></public-module>
	<view v-if="shopinfo.shop_id>0">
	<view class="imagebox ">
		<view :style="'background-image: url('+shopinfo.cover_url+');'" class="image-bg"></view>
		<view class="u-flex-y u-flex-middle u-m-t-50">
			<u--image :src="shopinfo.shopqrcode" width="120px" height="120px" radius="10"></u--image>
			<!--button type="primary" size="mini" @click="$Router.push({path: '/pages/componentsC/shop/postershop', query: {id: shopinfo.shop_id}})">生成海报</button-->
		</view>
	</view>
		<!--view class="u-margin-20">
			<u-alert type="warning" :description="ztinfo"></u-alert>
		</view-->
		<u-gap height="8" bg-color="#f3f4f6"></u-gap>
	</view>

	<view class="u-padding-20">
		<u--form labelPosition="left" labelWidth="40" >
			<u-form-item label="名称" >
				<u-input placeholder="可选填" type="text" v-model="shopinfo.name"/>
			</u-form-item>
			<u-form-item label="副标" borderBottom>
				<u-input placeholder="可选填" type="text" v-model="shopinfo.title"/>
			</u-form-item>
			
			<u-form-item label="类别">
				  <u-radio-group v-model="shopinfo.orderType" placement="row" @change="radioGroupChange">
					<u-radio v-for="(ordertype, index) in orderTypelist"
						@change="radioChange"
						:label="ordertype.txt"
						:key="index"
						:labelSize="16" :size="16"
						:customStyle="{marginRight: '15px'}"
						:name="ordertype.name">
					</u-radio>
				  </u-radio-group>
			</u-form-item>
			<view class="u-p-b-20 u-flex u-flex-fill u-flex-middle u-info">
			{{intro}}
			</view>
			<view class="b-b"></view>
	<u-form-item label="外卖最少金额" labelWidth="100" v-if="shopinfo.orderType==3">
		<u-input placeholder="外卖模式最少订单金额" type="text" v-model="shopinfo.min_price"/>
		<text slot="right" style="font-size: 22rpx;color: #007AFF;" class="u-p-l-20">元</text>
	</u-form-item>
	<u-form-item label="配送费" labelWidth="60" borderBottom v-if="shopinfo.orderType==3">
		<view class="u-flex  u-flex-middle">
			<view class="u-flex-3">
				<u-input placeholder="配送费" type="text" v-model="shopinfo.delivery_cost"/>
			</view>
			<view class="u-flex-2">
				<u--text text="包装费" align="center"></u--text>
			</view>
			<view class="u-flex-4">
				<u-input placeholder="包装费" type="text" v-model="shopinfo.packing_fee"/>
			</view>
		</view>
	</u-form-item>
				<view class="u-flex u-m-b-20 u-p-t-20">
					<view class="u-flex-2">地址</view>
					<view class="u-flex-10">
						<view class="u-flex u-flex-fill">
							<view><u-button size="mini" :hairLine="false" type="warning" @click="addaddress_pop=true">添加地址</u-button></view>
							<view class="u-m-l-20"><u-button size="mini" :hairLine="false" type="warning" @click="edit_addaddress_pop=true">修改地址</u-button></view>
						</view>
						<u-gap height="8"></u-gap>
						<view class="u-flex u-flex-fill">
						<u-checkbox-group v-model="addrid_array"
							placement="column"
							@change="checkboxChange">
							<u-checkbox :customStyle="{marginTop: '8px'}"
								v-for="(item, index) in addressList"
								:key="index"
								:label="item.address"
								:name="''+item.addr_id+''">
							</u-checkbox>
						</u-checkbox-group>
						</view>
					</view>
				</view>
				<view class="b-b"></view>
	
			
<!-- 			<u-form-item label="类别"  v-if="shopinfo.shop_id==''||shopinfo.shop_id==null" v-else>
				{{shopinfo.orderType_txt}}
			</u-form-item> -->
			


			<u-form-item label="简介">
				<editor id="editor" class="editor-container" placeholder="请输入内容" @input="getEditorContent" @ready="onEditorReady"></editor>
			</u-form-item>
			<!--u-form-item label="收款方式" labelWidth="70" borderBottom>
				  <u-radio-group v-model="paymentMethod" placement="column" @change="radioChange_paymentMethod">
					<u-radio v-for="(paymeth, index) in paymentMethodList"
						:label="paymeth.txt"
						:key="index"
						:labelSize="16" :size="16"
						:customStyle="{marginBottom: '8px',marginTop: '8px'}"
						:disabled="paymeth.disabled"
						:name="paymeth.name">
					</u-radio>
				  </u-radio-group>
			</u-form-item-->
			<u-form-item label="收款" borderBottom v-if="ordertype==2">
					<u-upload 
						:fileList="fileList3"
						@afterRead="afterRead"
						maxCount="2"
						@delete="deletePic"
						name="3"
						width="60"
						height="60">
					</u-upload>
				<view>上传收款码或微信二维码</view>
			</u-form-item>
			<u-form-item label="封面" borderBottom>
					<u-upload 
						:fileList="fileList1"
						@afterRead="afterRead"
						maxCount="1"
						@delete="deletePic"
						name="1"
						width="60"
						height="60">
					</u-upload>
			</u-form-item>
			
			<u-form-item label="幻灯" :borderBottom="false">
					<u-upload 
						:fileList="fileList2"
						@afterRead="afterRead"
						maxCount="5"
						@delete="deletePic"
						name="2"
						width="60"
						height="60">
					</u-upload>
			</u-form-item>

		</u--form>
	</view>
		<u-gap height="16" bg-color="#f3f4f6"></u-gap>
			<view class="u-m-t-10 u-padding-20">
				<u-button type="primary" @click="submit()">确定</u-button>
				<u-gap height="30"></u-gap>
				<!--u-button type="error" @click="delshop()" v-if="shopinfo.shop_id>0">删除此店铺</u-button>
				<u-gap height="80"></u-gap-->
			</view>
			
		
		<u-popup :customStyle="{width: '96%',padding:'6px 10px'}" :round="10" :show="addaddress_pop" @close="addaddress_pop = false" mode="center" closeOnClickOverlay>
		<view class="modal-content">
			<u--form class="u-m-b-20 numinput" label-position="left" label-width="80">
				<u-form-item class="form-item" label="联系人" >
					<u--input v-model="addressData.consignee" placeholder="请填写收货人姓名"/>
				</u-form-item>
				<u-form-item class="form-item" label="手机号码">
					<u--input v-model="addressData.mobile" placeholder="请填写收货人手机号"/>
				</u-form-item>
				<!--u-form-item class="form-item" label="所在地区">
					<input disabled type="text" :value="input" placeholder-class="line" placeholder="省市区县、乡镇等"  @tap="showRegionPicker"/>
				</u-form-item-->
				<u-form-item class="form-item" label="物业名字">
				<text @click="chooseLocation" class="input">
				选择：</text>
				</u-form-item>
				<u-form-item class="form-item" label="地址">
					<u--input v-model="addressData.address" placeholder="街道、楼牌等"/>
				</u-form-item>
				<u-button type="primary" @click="submit_addaddress">确认设置</u-button>
			</u--form>
		</view>
		</u-popup>	

		<u-popup :customStyle="{width: '96%',padding:'6px 10px'}" :round="10" :show="edit_addaddress_pop" @close="edit_addaddress_pop = false" mode="center" closeOnClickOverlay>
		<view class="modal-content">
			<scroll-view scroll-y="true"  style="height: 620rpx;">
				<view class="base-tonglan-box">
				<view class="u-flex item" v-for="(item, index) in addressList">
					<view class="u-flex-8 u-line-1">{{item.address}}</view>
					<view class="u-flex-2" @click="edit_addaddress_pop=false;get_address_info(item.addr_id)">修改</view>
					<view class="u-flex-2" @click="del_address(item.addr_id)">删除</view>
				</view>
				</view>
			</scroll-view>
		</view>
		</u-popup>	

  </view>
</template>


<script>
import { mapState, mapMutations } from "vuex";
import base from "@/config/baseUrl";
import { uploadFilePromise } from '@/plugins/upload/upload';
import { api_shopInfo,api_user_addresslist,api_user_addresssave,api_user_addressinfo,api_user_addressdel,api_storemanage_save } from '@/config/api.js';
export default {
  data() {
    return {
      fileList1:[],
	  fileList2:[],
	  fileList3:[],
      flow_list: [],
      paystatus:false,
      loadstxt: "loading...",
	  shopinfo: [],
	  sendname:'',
	  addressData: {
		  addr_id:'',
		  consignee:'',
		  address:'',
		  mobile:'',
		  lat:'',
		  lng:''
	  },
	  addrid_array:[],
	  		ordertype:1,
			paymentMethodList:[{
					txt: '添加收款码图片',
					name:2,
					disabled: false
			}],
			orderTypelist: [
				{
					txt: '票券',
					disabled: false,
					name:0,
					intro:'购买生成专用唯一二维码，通过手机扫一扫核销。'
				},
				{
					txt: '快递',
					disabled: false,
					name:1,
					intro:'仅物流快递寄送'
				},
				{
					txt: '服务',
					disabled: false,
					name:2,
					intro:'服务类别'
				},
				{
					txt: '自取外卖',
					disabled: false,
					name:3,
					intro:'在店自取或外卖型'
				}
			],
			// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
			orderTypevalue: 1,
			ztinfo:'小程序展位状态：',
			addressList:[],
			edit_addaddress_pop:false,
			addaddress_pop:false,
			intro:'请选择 ↑',
			ordertype:1
    };
  },
  computed: {
    ...mapState(["userIndex"]),
  },
  watch: {
	addaddress_pop(newValue, oldValue) {
		if (newValue==false)this.addressData=[]
	},
  },
   onLoad(options) {
	    this.shop_id = options.shop_id;
	    this.get_shopinfo(this.shop_id);
		let newPayitem={
			txt:'官方提供,帐号:',
			name:1,
			disabled: false
		};
		this.paymentMethodList.push(newPayitem);
  },

  methods: {
	  del_address(addrid){
		  if (addrid){
			this.$api('order.address_del', {
				addr_id:addrid,
				shop_id:this.shop_id
			}).then(res => {
				if (res.code==200){
					this.$tools.msg('地址已删除');
					setTimeout(() => {
								this.edit_addaddress_pop=false;
								this.refreshList()
					}, 400);
				}
			}).catch((e)=>{});	
		  }
	  },
	  get_address_info(addrid){
		  this.addaddress_pop=true
			api_user_addressinfo({
					addr_id:addrid
			}).then(res => {
					this.addressData=res
					
			}).catch((e)=>{});	
	  },

    chooseLocation() {
      uni.chooseLocation({
        success: data => {
		  this.addressData.address = data.address;
		  this.addressData.lat = data.latitude;
		  this.addressData.lng = data.longitude;
        }
      });
    },
	submit_addaddress(){
		var aData={
			...this.addressData,
			shop_id:this.shop_id,
			is_default:false,
			addr_id:this.addressData.addr_id?this.addressData.addr_id:''
		}
		console.log(JSON.stringify(aData))
		api_user_addresssave({
			model:JSON.stringify(aData)
		}).then((res) => {
					this.$tools.msg(
						`地址${this.addr_id == "" ? "添加" : "修改"}成功`
					);
					setTimeout(() => {
						this.addaddress_pop=false;
						this.refreshList()
					}, 400);
		}).catch((e)=>{});
	},
	refreshList(data, type) {
	    api_user_addresslist({
			find_shop_id:this.shop_id
		},{custom: {load:false}}).then((res) => {
	          this.addressList = Array.isArray(res.roomlist) ? res.roomlist : [];
	    }).catch((e) => {});
	},
        onEditorReady() {/////////////////////////初始化
                uni.createSelectorQuery().select('#editor').context((res) => {
                    var contentVal_1 = this.shopinfo.content;
                    //将内容写入编辑器
                    this.editorCtx = res.context;
                    let EContent = {
                        html: contentVal_1
                    }
                    this.editorCtx.setContents(EContent); //设置富文本编辑器的内容
                }).exec()
            },
            getEditorContent(e) {/////////////////////////获取编辑器内容，当前页面都能获取到
                this.shopinfo.content = e.detail.html;
            },
		checkboxChange(e){
			this.shopinfo.addr_id=e.join(",")
			console.log(e);
		},
		radioChange(e) {
			 //console.log(e);
		},
		// 选中任一radio时，由radio-group触发
		radioChange_paymentMethod(e){
			console.log(e)
			this.ordertype=e
		},
		radioGroupChange(e) {
			this.paymentMethodList[0].disabled=false
			this.intro=this.orderTypelist[e].intro
			this.refreshList()
			 if (e==3||e==0){
				 this.ordertype=1
				 this.paymentMethodList[0].disabled=true
			 }
		},
	get_shopinfo(shop_id){
        api_shopInfo({params:{shop_id:shop_id}}).then(res => {
			console.log(res)
			if (res.shop_id>0){
				this.shopinfo=res
				this.ordertype=this.shopinfo.ordertype
				this.onEditorReady()
				this.addrid_array=this.shopinfo.addr_id.split(',')
				//this.content=res.content
				if (res.cover_url!=''){
					this.fileList1.push({
						file_id:res.cover_id,
						url:res.cover_url,
					})
				}
				res.images.map((item) => {
					console.log(item)
					this.fileList2.push({
						file_id:item.file_id,
						url:item.file_url
					})
				})
				if (this.shopinfo.is_rec==1){
					this.ztinfo=this.ztinfo+'小程序页面推广中'
				}else{
					this.ztinfo=this.ztinfo+'自主分享【推广请联系管理员】'
				}
				this.refreshList()
			}else{
				uni.setNavigationBarTitle({title: "创建"});
			}
        }).catch((e)=>{});
	},
			
	submit(){
		console.log(this.fileList2)
		var cover_id = ''
		if (this.fileList1.length>0){
			this.fileList1.map((item) => {
				cover_id=item.file_id
			})
		}
		let images = []
		this.fileList2.map((item) => {
			images.push({
				file_url:item.url,
				file_id:item.file_id
			})
		})
		
		let data={
			...this.shopinfo,
			cover_id:cover_id,
			images_ids:JSON.stringify(images)
		}
		console.log('data',data)
		api_storemanage_save(data).then((res) => {
			console.log(res)
			//uni.reLaunch({url: '/pages/componentsC/shop/storemanage/index'})
		}).catch((e) => {});
	},
	delshop(){
		this.$api("shopstore.shop_del", {
			shop_id: this.shop_id
		}).then((res) => {
			if (res.code==200){
					this.$Router.push("/pages/componentsC/shop/storemanage/index");
				}else{
					this.$u.toast(res.msg);
			}}).catch((e) => {});
	},
	


			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await uploadFilePromise(lists[i].url,2)
					let item = this[`fileList${event.name}`][fileListLen]
					
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						file_id: result.file_id,
						url: result.file_url
					}))
					//this[`fileList${event.name}`][fileListLen].url=result
					fileListLen++
				}
			},

  },
};
</script>
<style lang="scss" scoped>
	.editor-container{
		border: solid 1px #cccccc;
		padding:5px
	}
.imagebox{
	position: absolute;
	top:0;
	left:0;
	height: 370rpx;
	width: 100%;
	overflow: hidden;
	position: relative;
}
.image-bg {
    position: absolute;
    left: -5%;
    bottom: 0;
	top:-40rpx;
    right: 0;
	filter:blur(8px);
}
.qrcode{
	margin:40rpx auto 20rpx auto;
	display: inline-block;
}
</style>
